package cn.stylefeng.guns.sys.modular.system.controller;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.modular.system.db4.entity.Team;
import cn.stylefeng.guns.sys.modular.system.db4.mapper.TeamMapper;
import cn.stylefeng.guns.sys.modular.system.db4.service.TeamService;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyBxdMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.UserMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.ProjectParam;
import cn.stylefeng.guns.sys.modular.system.model.params.TaskStatusParam;
import cn.stylefeng.guns.sys.modular.system.service.*;
import cn.stylefeng.guns.sys.modular.system.warpper.NoticeWrapper;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * 工程微信公众号端
 */
@CrossOrigin
@Controller
@RequestMapping("/gcWx")
public class GcWxController {

    private static Logger logger = LoggerFactory.getLogger(GcWxController.class);

    @Resource
    private UserMapper userMapper;
    @Autowired
    private GcWxService gcWxService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private TaskStatusService taskStatusService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private TeamService teamService;
    @Autowired
    private BtyWageService btyWageService;
    @Autowired
    private DictService dictService;
    @Resource
    private TeamMapper teamMapper;
    @Autowired
    private BtyBxdService btyBxdService;
    @Autowired
    private BtyBxdMapper btyBxdMapper;

//    public static Map<String,Map> commData= new HashMap<String,Map>();
//    public static MultiValueMap commData = new LinkedMultiValueMap();

    public static List<Object> commList = new ArrayList<>();
    public static List<Map> openId = new ArrayList<>();
//    public static String openId;

    private static String open = "1";//1开，2关

    /**
     *根据code获取用户信息
     * @param request
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/getUserByCode")
    public Object getUserByCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{

        //从request里面获取code参数(当微信服务器访问回调地址的时候，会把code参数传递过来)
        String code = request.getHeader("code");

        Map map = loginService.get(code);

        JSONObject r = new JSONObject();

        //获取用户信息
        if (map != null && map.get("userId") != null){
            //根据userID获取用户信息
            Map userMap = userMapper.getUserByCode(Long.valueOf(String.valueOf(map.get("userId"))));
            userMap.put("token",map.get("token"));

            String userId = userMap.get("sm_user_id").toString();
            userMap.put("sm_user_id", userId);

//            commData.put("token",userMap);
//            commData.put("token",  new ArrayList(userMap.values()));
            commList.add(map.get("token"));
            if (ToolUtil.isNotEmpty(map.get("openid"))){
//                openId = map.get("openid").toString();
                Map map1 = new HashMap<>();
                map1.put("openid",map.get("openid"));
                map1.put("token",map.get("token"));

//                openId.add(map.get("openid"));
//                openId.add(map.get("token"));
                openId.add(map1);
            }

            r.put("data",JSON.toJSONString(userMap));
            r.put("token",code);
            r.put("success",true);
            logger.info(r + "[[[[[[[[[[[[[");

            //用户openid
        }else if(map != null && map.get("openid") != null){

            commList.add(map.get("token"));
            if (ToolUtil.isNotEmpty(map.get("openid"))){
                Map map1 = new HashMap<>();
                map1.put("openid",map.get("openid"));
                map1.put("token",map.get("token"));
                openId.add(map1);
            }

            r.put("data",new String[0]);
            r.put("token",code);
            r.put("success",true);
            logger.info(r + "]]]]]]]]]]]]]");

        }else {
            r.put("success",false);
        }
        return r.toJSONString();

    }


    /**
     *  本店未完成任务列表
     * @param proId 工程id
     * @return
     */
    @ResponseBody
    @RequestMapping("/noFinish")
    public Map noFinish(HttpServletRequest request, int proId, Long userId) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            if (code.equals(mailValue)){
                return this.gcWxService.noFinish(proId,userId);
            }
        }

//        return this.gcWxService.noFinish(proId,userId);
        return null;

    }


    /**
     *  本店已完成任务列表
     * @param proId 工程id
     * @return
     */
    @ResponseBody
    @RequestMapping("/finish")
    public List finish(HttpServletRequest request, int proId) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            if (code.equals(mailValue)){
                return this.gcWxService.finish(proId);
            }
        }

        return null;
//        return this.gcWxService.finish(proId);

    }




    /**
     *  全部店已完成任务列表
     * @return
     */
    @ResponseBody
    @RequestMapping("/finishShop")
    public ResponseData finishShop(HttpServletRequest request, Long userId, String proName) {
        String wxOpenId = null;

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            if (code.equals(mailValue)){
                return this.gcWxService.finishShop(wxOpenId, userId, proName);
            }
        }

//        return this.gcWxService.finishShop(wxOpenId, userId);
        return null;

    }




    /**
     *  全部店未完成任务列表
     * @return
     */
    @ResponseBody
    @RequestMapping("/noFinishShop")
    public List noFinishShop(HttpServletRequest request, Long userId, String proName) {
        String wxOpenId = null;

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            if (code.equals(mailValue)){
                return this.gcWxService.noFinishShop(wxOpenId, userId, proName);
            }
        }

//        return this.gcWxService.noFinishShop(wxOpenId, userId);
        return null;

    }



    /**
     * 新增任务信息(营运)
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/addRent")
    public ResponseData addRent(@RequestBody List<TaskStatus> taskStatus, HttpServletRequest request) throws Exception {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            if (code.equals(mailValue)){
                this.gcWxService.addRent(taskStatus);
                return ResponseData.success();
            }
        }

        return null;

//        this.gcWxService.addRent(taskStatus);
//        return ResponseData.success();

    }


    /**
     * 收银系统建档
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/archives")
    public ResponseData archives(@RequestBody List<TaskStatus> taskStatus, HttpServletRequest request) throws Exception {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            if (code.equals(mailValue)){
                this.gcWxService.archives(taskStatus);
            }
        }

//        this.gcWxService.archives(taskStatus);

        return null;

    }


    /**
     * 查看当前任务信息
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/taskList")
    public ResponseData taskList(int proId, int taskId, HttpServletRequest request, Long userId) {
        String wxOpenId = null;

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            logger.info("mailValue====="+mailValue + "========="+ iter + "--------" + code);
            if (code.equals(mailValue)){
//                Map list = this.gcWxService.taskList(proId, taskId, wxOpenId, userId);
                List<TaskStatus> list = this.gcWxService.taskList(proId, taskId, wxOpenId, userId);
                return ResponseData.success(list);
            }
        }

        return null;

//        List<TaskStatus> list = this.gcWxService.taskList(proId, taskId, wxOpenId, userId);
//        return ResponseData.success(list);

    }


    /**
     * 新增任务信息(工程)
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/addPro")
    public ResponseData addPro(@RequestBody List<TaskStatus> taskStatus, HttpServletRequest request) throws Exception {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            if (code.equals(mailValue)){
                this.gcWxService.addPro(taskStatus);
                return ResponseData.success();
            }
        }

        return null;

//        this.gcWxService.addPro(taskStatus);
//        return ResponseData.success();
    }


    /**
     *  全部店已完成任务列表(工程)
     * @return
     */
    @ResponseBody
    @RequestMapping("/GCFinish")
    public ResponseData GCFinish(HttpServletRequest request, Long userId, String proName) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            if (code.equals(mailValue)){
                //排除现场踏勘任务
                List<Map> list = gcWxService.GCFinish(userId, proName);
                return ResponseData.success(list);
            }
        }
        return null;

    }




    /**
     *  全部店未完成任务列表（工程）
     * @return
     */
    @ResponseBody
    @RequestMapping("/GCNoFinish")
    public List GCNoFinish(HttpServletRequest request, Long userId, String proName) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            if (code.equals(mailValue)){
                //排除现场踏勘任务
                return this.gcWxService.GCNoFinish(userId, proName);
            }
        }
        return null;

//        return this.gcWxService.GCNoFinish(userId, proName);

    }


    /**
     *  本店未完成任务列表（工程）
     * @param proId 工程id
     * @return
     */
    @ResponseBody
    @RequestMapping("/noFinishGc")
    public ResponseData noFinishGc(HttpServletRequest request, int proId, Long userId) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            if (code.equals(mailValue)){
                Map map = this.gcWxService.noFinishGc(proId,userId);
                return ResponseData.success(map);
            }
        }

        return null;

//        Map map = this.gcWxService.noFinishGc(proId,userId);
//        return ResponseData.success(map);

    }


    /**
     *  本店已完成任务列表（工程）
     * @param proId 工程id
     * @return
     */
    @ResponseBody
    @RequestMapping("/finishGc")
    public ResponseData finishGc(HttpServletRequest request, int proId, Integer taskId, Long userId) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            if (code.equals(mailValue)){
                List list = this.gcWxService.finishGc(proId, taskId, userId);
                return ResponseData.success(list);
            }
        }

        return null;

//        List list = this.gcWxService.finishGc(proId, taskId, userId);
//        return ResponseData.success(list);

    }


    /**
     * 查看当前任务信息(工程)
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/GCList")
    public ResponseData GCList(int proId, int taskId, HttpServletRequest request, Long userId) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            logger.info("mailValue====="+mailValue + "========="+ iter);
            if (code.equals(mailValue)){

                Map map = this.gcWxService.GCList(proId, taskId, userId);
                return ResponseData.success(map);
            }
        }

        return null;

//        Map map = this.gcWxService.GCList(proId, taskId, userId);
//        return ResponseData.success(map);

    }

    /**
     * 已指定营运经理店铺
     * @param request
     * @return
     */
    @ResponseBody
    @GetMapping("/yYList")
    public ResponseData yYList(HttpServletRequest request, String proName) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            logger.info("mailValue====="+mailValue + "========="+ iter);
            if (code.equals(mailValue)){

                List list = this.gcWxService.yYList(proName);
                return ResponseData.success(list);
            }
        }

        return null;

//        List list = this.gcWxService.yYList(proName);
//        return ResponseData.success(list);

    }

    /**
     * 未指定营运经理店铺
     * @param request
     * @return
     */
    @ResponseBody
    @GetMapping("/yYNoList")
    public ResponseData yYNoList(HttpServletRequest request,String proName) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            logger.info("mailValue====="+mailValue + "========="+ iter);
            if (code.equals(mailValue)){

                List list = this.gcWxService.yYNoList(proName);
                return ResponseData.success(list);
            }
        }

        return null;

//        List list = this.gcWxService.yYNoList(proName);
//        return ResponseData.success(list);

    }

    /**
     * 查询督导列表
     *
     * @return
     */
    @GetMapping("/selectDdList")
    @ResponseBody
    public ResponseData selectDdList(HttpServletRequest request, Long userId) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            logger.info("mailValue====="+mailValue + "========="+ iter);
            if (code.equals(mailValue)){

                //根据userID获取phone
                String phone = userMapper.getPhone(userId);

//                List list = projectService.selectDdList(phone);
                List list = teamService.selectDdList(phone);
                return ResponseData.success(list);
            }
        }
        return null;

//        String phone = userMapper.getPhone(userId);
//        List list = teamService.selectDdList(phone);
//        return ResponseData.success(list);

    }

    /**
     * 查询营运经理列表
     *
     * @return
     */
    @GetMapping("/selectYyjlList")
    @ResponseBody
    public ResponseData selectYyjlList(HttpServletRequest request) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            logger.info("mailValue====="+mailValue + "========="+ iter);
            if (code.equals(mailValue)){

//                List list = projectService.selectYyjlList();
                List list = teamService.selectYyjlList();
                return ResponseData.success(list);
            }
        }

        return null;

//        List list = teamService.selectYyjlList();
//        return ResponseData.success(list);
    }

    /**
     * 已指定督导店铺
     * @param request
     * @return
     */
    @ResponseBody
    @GetMapping("/dDList")
    public ResponseData dDList(HttpServletRequest request, String proName, Long userId) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            logger.info("mailValue====="+mailValue + "========="+ iter);
            if (code.equals(mailValue)){

                List list = this.gcWxService.dDList(proName, userId);
                return ResponseData.success(list);
            }
        }

        return null;

//        List list = this.gcWxService.dDList(proName, userId);
//        return ResponseData.success(list);

    }

    /**
     * 未指定督导店铺
     * @param request
     * @return
     */
    @ResponseBody
    @GetMapping("/dDNoList")
    public ResponseData dDNoList(HttpServletRequest request,String proName, Long userId) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            logger.info("mailValue====="+mailValue + "========="+ iter);
            if (code.equals(mailValue)){

                List list = this.gcWxService.dDNoList(proName, userId);
                return ResponseData.success(list);
            }
        }

        return null;

//        List list = this.gcWxService.dDNoList(proName, userId);
//        return ResponseData.success(list);

    }

    /**
     * 指定营运经理
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("/saveYy")
    public ResponseData saveYy(HttpServletRequest request, ProjectParam record) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            logger.info("mailValue====="+mailValue + "========="+ iter);
            if (code.equals(mailValue)){

                ResponseData responseData = projectService.saveGcWxyyjl(record);
                return responseData;
            }
        }

        return null;

//        ResponseData responseData = projectService.saveGcWxyyjl(record);
//        return responseData;

    }

    /**
     * 指定督导
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("/saveDd")
    public ResponseData saveDd(HttpServletRequest request, ProjectParam record) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            logger.info("mailValue====="+mailValue + "========="+ iter);
            if (code.equals(mailValue)){

                ResponseData responseData = projectService.saveGcWxDd(record);
                return responseData;
            }
        }

        return null;

//        ResponseData responseData = projectService.saveGcWxDd(record);
//        return responseData;

    }

    /**
     * 本店营运经理
     * @param request
     * @return
     */
    @ResponseBody
    @GetMapping("/yyShop")
    public ResponseData yyShop(HttpServletRequest request,Integer proId) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            logger.info("mailValue====="+mailValue + "========="+ iter);
            if (code.equals(mailValue)){

                List list = this.gcWxService.yyShop(proId);
                return ResponseData.success(list);
            }
        }

        return null;


//        List list = this.gcWxService.yyShop(proId);
//        return ResponseData.success(list);

    }

    /**
     * 本店督导
     * @param request
     * @return
     */
    @ResponseBody
    @GetMapping("/ddShop")
    public ResponseData ddShop(HttpServletRequest request,Integer proId) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            logger.info("mailValue====="+mailValue + "========="+ iter);
            if (code.equals(mailValue)){

                List list = this.gcWxService.ddShop(proId);
                return ResponseData.success(list);
            }
        }

        return null;

//        List list = this.gcWxService.ddShop(proId);
//        return ResponseData.success(list);

    }

    /**
     * 确认开店
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("/audit")
    public ResponseData audit(HttpServletRequest request, TaskStatusParam taskStatusParam) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            logger.info("mailValue====="+mailValue + "========="+ iter);
            if (code.equals(mailValue)){

                taskStatusParam.setTaskId(7);//营运总监确认
                taskStatusService.audit(taskStatusParam);
                return ResponseData.success();
            }
        }

        return null;

//        taskStatusParam.setTaskId(7);//营运总监确认
//        taskStatusService.audit(taskStatusParam);
//        return ResponseData.success();

    }

    /**
     * 判断本店任务进度状态
     * @param request
     * @return
     */
    @ResponseBody
    @GetMapping("/dmStatus")
    public ResponseData dmStatus(HttpServletRequest request,Integer proId) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            logger.info("mailValue====="+mailValue + "========="+ iter);
            if (code.equals(mailValue)){

                Map map = this.gcWxService.dmStatus(proId);
                return ResponseData.success(map);
            }
        }

        return null;

//        Map map = this.gcWxService.dmStatus(proId);
//        return ResponseData.success(map);

    }



    /**
     * 修改任务信息
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/editRent")
    public ResponseData editRent(@RequestBody List<TaskStatus> taskStatus, HttpServletRequest request) throws Exception {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            if (code.equals(mailValue)){
                taskService.editRent(taskStatus);
                return ResponseData.success();
            }
        }

        return null;

//        taskService.editRent(taskStatus);
//        return ResponseData.success();
    }


    /**
     * 判断当前任务登录人角色
     * @param request
     * @return
     */
    @ResponseBody
    @GetMapping("/roleStatus")
    public ResponseData roleStatus(HttpServletRequest request,Integer proId, Long userId) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            logger.info("mailValue====="+mailValue + "========="+ iter);
            if (code.equals(mailValue)){

                Map map = this.gcWxService.roleStatus(proId, userId);
                return ResponseData.success(map);
            }
        }

        return null;

//        Map map = this.gcWxService.roleStatus(proId, userId);
//        return ResponseData.success(map);

    }


    /**
     * 修改现场踏勘推迟日期
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/editXctk")
    public ResponseData editXctk(Integer proId, String xctk, HttpServletRequest request) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            if (code.equals(mailValue)){
                gcWxService.editXctk(proId, xctk);
                return ResponseData.success();
            }
        }

        return null;

//        gcWxService.editXctk(proId, xctk);
//        return ResponseData.success();
    }

    /**
     * 查询现场踏勘推迟日期
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getXctk")
    public ResponseData getXctk(Integer proId, HttpServletRequest request) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            logger.info("mailValue====="+mailValue + "========="+ iter + "-------------" + code);
            if (code.equals(mailValue)){
                logger.info("((((((((((((" + code);
                Map project = gcWxService.getXctk(proId);
                return ResponseData.success(project);
            }
        }

        return null;

    }

    /**
     * 确认到货修改
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/editDh")
    public ResponseData editDh(@RequestBody List<TaskStatus> taskStatus, HttpServletRequest request) throws ParseException  {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            logger.info("mailValue====="+mailValue + "========="+ iter + "-------------" + code);
            if (code.equals(mailValue)){
                logger.info("((((((((((((" + code);
//                taskService.editDh(proId);
                taskService.editRent(taskStatus);
                return ResponseData.success();
            }
        }

        return null;

//        taskService.editRent(taskStatus);
//        return ResponseData.success();

    }

    /**
     * 确认到货状态
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getDh")
    public ResponseData getDh(Integer proId, HttpServletRequest request) {

        String code = request.getHeader("code");

        Iterator<Object> iter = commList.iterator();
        while (iter.hasNext()){
            String mailValue = (String) iter.next();
            logger.info("mailValue====="+mailValue + "========="+ iter + "-------------" + code);
            if (code.equals(mailValue)){
                logger.info("((((((((((((" + code);
                Map map = gcWxService.getDh(proId);
                return ResponseData.success(map);
            }
        }

        return null;

//        Map map = gcWxService.getDh(proId);
//        return ResponseData.success(map);

    }



    /**
     * 工资审核页面列表
     *
     */
    @RequestMapping(value = "/shgzList")
    @ResponseBody
    public Object shgzList(String account, String condition,String dm,String status) {
        Map<Object, Object> map = new HashMap<>();
        List list = new ArrayList();

        if (ToolUtil.isNotEmpty(account)){
            //获取用户角色
            User user = userMapper.getByAccount(account);
            Team role = teamMapper.getName(account);

            String username = null;
            String roleId = null;
            List rolds = new ArrayList<>();
            List<String> roleNames = new ArrayList<>();

            if (ToolUtil.isNotEmpty(user)){
                username = user.getName();//用户名字
                roleId = user.getRoleId();//用户角色id
                rolds = Arrays.asList(roleId.split(","));
                //获取用户角色名称
                roleNames = userMapper.getRole(rolds);
            }
            else if (ToolUtil.isNotEmpty(role)){
                username = role.getName();
            }

            if (ToolUtil.isNotEmpty(user) || ToolUtil.isNotEmpty(role)){

                //获取当前月的上个月
                String lastMonth = DateUtil.getLastMonth();
                String roleName = "人事";
                String flag = "";

                if(roleNames.contains("督导") || (ToolUtil.isNotEmpty(role) && (role.getRankName().equals("大店长") || role.getRankName().equals("督导")))){
                    map.put("role", 1);
                }else {
                    map.put("role", 0);
                }

                if(roleNames.contains(roleName)){
                    list = this.btyWageService.listGz(condition,dm,null,lastMonth,status,null,null,flag);
                    map.put("data", list);
                    map.put("success",true);
                    map.put("msg",null);
                    return map;
                }

                if(!("admin".equals(account)) && !roleNames.contains("营运总监") && ToolUtil.isNotEmpty(roleNames) ||
                        (ToolUtil.isNotEmpty(role) && !role.getRankName().equals("营运总监"))){
                    flag="8";
                    //根据姓名查询是否是督导
                    if(!roleNames.contains("督导")){
                        list = this.btyWageService.listGz(condition,dm,null,lastMonth,status,username,null,flag);
                        if(list.size() == 0){
                            list = this.btyWageService.listGz(condition,dm,account,lastMonth,status,null,null,flag);
                        }
                        map.put("data", list);
                        map.put("success",true);
                        map.put("msg",null);
                    }else{
                        list = this.btyWageService.listGz(condition,dm,null,lastMonth,status,null,username,flag);
                        if(list.size() == 0){
                            list = this.btyWageService.listGz(condition,dm,account,lastMonth,status,null,username,flag);
                        }
                        map.put("data", list);
                        map.put("success",true);
                        map.put("msg",null);
                    }
                }
                else{
                    list = this.btyWageService.listGz(condition,dm,null,lastMonth,status,null,null,flag);
                    map.put("data", list);
                    map.put("success",true);
                    map.put("msg",null);
                }
            }else {
                map.put("role", 0);
                map.put("data", list);
                map.put("success",false);
                map.put("msg","未获取用户账号信息！");
            }

        }else {
            map.put("role", 0);
            map.put("data", list);
            map.put("success",false);
            map.put("msg","未获取用户账号信息！");
        }

        return map;
    }

    /**
     * 工资审核页面查询店名
     *
     */
    @RequestMapping(value = "/getDm")
    @ResponseBody
    public List<Map> getDictionaryType(String account){

        List<Map> list = null;

        if (ToolUtil.isNotEmpty(account)){
            //获取用户角色
            User user = userMapper.getByAccount(account);
            Team role = teamMapper.getName(account);

            if (ToolUtil.isNotEmpty(user) || ToolUtil.isNotEmpty(role)){
                String userName = null;
                String roleId = null;
                String phone = null;
                List roleNames = new ArrayList();

                if (ToolUtil.isNotEmpty(user)){
                    userName = user.getName();//用户名字
                    roleId = user.getRoleId();//用户角色id
                    phone = user.getPhone();//用户电话
                    List rolds = Arrays.asList(roleId.split(","));
                    //获取用户角色名称
                    roleNames = userMapper.getRole(rolds);
                }else if (ToolUtil.isNotEmpty(role)){
                    userName = role.getName();
                    phone = role.getMobile();
                }


                if(roleNames.contains("人事")){
                    userName="admin";
                    list = this.btyWageService.dmListMap(userName,null,null);
                    return list;
                }
                if(!("admin".equals(userName)) && !roleNames.contains("营运总监") && !role.getRankName().equals("营运总监")){
                    if(!roleNames.contains("督导")){
                        list = this.btyWageService.dmListMap(userName,null,null);
                        if(list.size()==0){
                            list = this.btyWageService.dmListMap(null,null,phone);
                        }
                    }else{
                        list = this.btyWageService.dmListMap(null,userName,null);
                        if(list.size()==0){
                            list = this.btyWageService.dmListMap(null,userName,phone);
                        }
                    }
                }else{
                    userName = "admin";
                    list = this.btyWageService.dmListMap(userName,null,null);
                }
            }

        }
        return list;
    }

    /**
     * 批量审核确认
     * @author liuy
     * @Date
     */
    @RequestMapping(value = "/confirmOk")
    @ResponseBody
    public Object confirmOk(@RequestParam String ids) {
        Map<Object, Object> map = new HashMap<>();

        if (ToolUtil.isNotEmpty(ids)){
            String[] idss = ids.split(",");
            for(String id:idss){
                BtyWage btyWage = btyWageService.getById(id);
                String bz = btyWage.getBz() == null ? "" : btyWage.getBz();
                String remark = bz + "9";
                btyWage.setBz(remark);
                btyWage.setUpdateTime(new Date());
                btyWageService.updateById(btyWage);
            }
            map.put("success",true);
            map.put("msg",null);
        }else {
            map.put("success",false);
            map.put("msg","请选择要审核的数据！");
        }

        return map;
    }
    /**
     * 批量取消审核
     * @author liuy
     * @Date
     */
    @RequestMapping(value = "/confirmQx")
    @ResponseBody
    public Object confirmQx(@RequestParam String ids) {
        Map<Object, Object> map = new HashMap<>();

        if (ToolUtil.isNotEmpty(ids)){
            String[] idss = ids.split(",");
            for(String id:idss){
                BtyWage btyWage = btyWageService.getById(id);
                String bz = btyWage.getBz() == null ? "" : btyWage.getBz();
                String remark = "";
                if(bz.contains("9")){
                    bz = bz.substring(0,bz.indexOf("9"));
                    remark = bz;
                }
                btyWage.setBz(remark);
                btyWage.setUpdateTime(new Date());
                btyWageService.updateById(btyWage);
            }
            map.put("success",true);
            map.put("msg",null);
        }else {
            map.put("success",false);
            map.put("msg","请选择要取消审核的数据！");
        }

        return map;
    }

    /**
     * 绑定用户
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("/bindUsers")
    public ResponseData bindUsers(HttpServletRequest request, HttpServletResponse response, String name, String phone, Long deptId) throws ServletException, IOException{

        String code = request.getHeader("code");

//        Iterator<Object> iter = commList.iterator();
        Iterator<Map> iter = openId.iterator();
        while (iter.hasNext()){
            Map mailValue = iter.next();
            logger.info("mailValue====="+mailValue + "========="+ iter);
            if (code.equals(mailValue.get("token"))){

                String openid = mailValue.get("openid").toString();
                Map map = this.gcWxService.bindUsers(name, phone, openid, deptId);
                return ResponseData.success(map);
            }
        }

        return null;

//        String openId = "oJnvX6VsSUxsvbJOKbZCVmNz9Scc";
//        Map map = this.gcWxService.bindUsers(name, phone, openId, deptId);
//        return ResponseData.success(map);

    }

    /**
     * 判断是否关注公众号，未关注跳转关注页
     * @param request
     * @return
     */
    @ResponseBody
    @GetMapping("/judge")
    public ResponseData judge(HttpServletRequest request, HttpServletResponse response) throws IOException{
        String code = request.getHeader("code");

        Iterator<Map> iter = openId.iterator();
        while (iter.hasNext()){
            Map mailValue = iter.next();
            logger.info("mailValue====="+mailValue + "========="+ iter);
            if (code.equals(mailValue.get("token"))){

                String openid = mailValue.get("openid").toString();

                //获取accessToken
                Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("code", "access_token"));
                String accessToken = "";
                if (ToolUtil.isNotEmpty(dict)) {
                    accessToken = dict.getName();
                }

                //获取用户登录基本信息
                RestTemplate restTemplate = new RestTemplate();
                String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openid + "&lang=zh_CN";
                String userInfo = restTemplate.getForObject(url, String.class);
                JSONObject jsonObject = JSONObject.parseObject(userInfo);
                logger.info("jsonObject====="+jsonObject);
                if(ToolUtil.isNotEmpty(jsonObject)){
                    Integer subscribe = Integer.valueOf(jsonObject.get("subscribe").toString());//0未关注；1已关注
                    logger.info("subscribe+++++++"+subscribe);
                    //用户未关注
                    if (subscribe == 0){
                        //跳转公众号关注页
                        response.sendRedirect("https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzIzOTAxMDA5OQ==&scene=110#wechat_redirect");
                        return ResponseData.success();
                    }
                }
            }
        }
        return ResponseData.success();
    }


    /**
     * 审批记录
     * （股份转让，银行卡，工资审批）
     */
    @ResponseBody
    @RequestMapping("/approveList")
    public ResponseData approveList(String account) {
        return this.gcWxService.approveList(account);
    }

    /**
     * 获取报销单列表
     */
    @RequestMapping(value = "/bxdList")
    @ResponseBody
    public LayuiPageInfo bxdList(String status, String flag, String beginTime, String endTime, String xm, String dm, String account,String brandId) {

        if (ToolUtil.isNotEmpty(endTime)) {
            endTime = endTime + " 23:59:59";
        }

        //根据电话获取用户角色
        User user = userMapper.getAccount(account);
        Team role = teamMapper.getName(account);

        String username = null;//用户名
        String roleId = null;
        List roleNames = new ArrayList();
        if (ToolUtil.isNotEmpty(user)){
            username = user.getAccount();
            roleId = user.getRoleId();//用户角色id
            List rolds = Arrays.asList(roleId.split(","));
            roleNames = userMapper.getRole(rolds);//用户角色
        }else if (ToolUtil.isNotEmpty(role)){
            username = role.getName();
        }
        List<String> ymList = null;//角色所对应的店的妖码

        String tel = "15215383999";//万总APP账号

        Page<Map<String, Object>> list = null;
        if (ToolUtil.isNotEmpty(user) || ToolUtil.isNotEmpty(role)){
            if (account.equals("admin") || "chujunjun".equals(username) || account.equals(tel) ||
                    (ToolUtil.isNotEmpty(roleNames) && (roleNames.contains("出纳") || roleNames.contains("总经理")))) {
                //查看所有
                list = this.btyBxdService.bxdList(status, flag, beginTime, endTime, dm, xm, null);

            } else if ((ToolUtil.isNotEmpty(roleNames) && roleNames.contains("营运经理")) ||
                    (ToolUtil.isNotEmpty(role) && role.getRankName().equals("营运经理"))) {
                ymList = teamMapper.getYyYms(account,brandId);//营运经理所有店
                if(ToolUtil.isNotEmpty(ymList)){
                    list = this.btyBxdService.bxdList(status, flag, beginTime, endTime, dm, xm, ymList);
                }

            } else if ((ToolUtil.isNotEmpty(roleNames) && roleNames.contains("督导")) ||
                    (ToolUtil.isNotEmpty(role) && role.getRankName().equals("督导"))) {
                ymList = teamMapper.getDdYms(account,brandId);//督导所有店

                if (ToolUtil.isNotEmpty(ymList)){
                    list = this.btyBxdService.bxdList(status, flag, beginTime, endTime, dm, xm, ymList);
                }

            } else if ((ToolUtil.isNotEmpty(roleNames) && roleNames.contains("大店长")) ||
                    (ToolUtil.isNotEmpty(role) && role.getRankName().equals("大店长"))) {
                ymList = teamMapper.getDdzYms(account,brandId);//大店长所有店

                if (ToolUtil.isNotEmpty(ymList)) {
                    list = this.btyBxdService.bxdList(status, flag, beginTime, endTime, dm, xm, ymList);
                }
            } else if ((ToolUtil.isNotEmpty(roleNames) && roleNames.contains("店长报销单管理")) ||
                    (ToolUtil.isNotEmpty(role) && role.getRankName().equals("店长"))) {
                ymList = teamMapper.getDzYms(account,brandId);//店长所有店

                if (ToolUtil.isNotEmpty(ymList)) {
                    list = this.btyBxdService.bxdList(status, flag, beginTime, endTime, dm, xm, ymList);
                }
            }
        }

        if (ToolUtil.isEmpty(list)){
            return new LayuiPageInfo();
        }
        Page<Map<String, Object>> wrap = new NoticeWrapper(list).wrap();
        return LayuiPageFactory.createPageInfo(wrap);
    }

    /**
     * 获取报销单当月总报销金额
     */
    @RequestMapping(value = "/bxdSum")
    @ResponseBody
    public ResponseData bxdSum(String status, String flag, String beginTime, String endTime, String xm, String dm, String account) {

        if (ToolUtil.isNotEmpty(endTime)) {
            endTime = endTime + " 23:59:59";
        }

        //根据电话获取用户角色
        User user = userMapper.getAccount(account);
        Team role = teamMapper.getName(account);

        String username = null;//用户名
        List roleNames = new ArrayList();
        if (ToolUtil.isNotEmpty(user)){
            username = user.getAccount();
            String roleId = user.getRoleId();//用户角色id
            List rolds = Arrays.asList(roleId.split(","));
            roleNames = userMapper.getRole(rolds);//用户角色
        }else if (ToolUtil.isNotEmpty(role)){
            username = role.getName();
        }
        List<String> ymList = null;//角色所对应的店的妖码

        String tel = "15215383999";//万总APP账号

        BigDecimal sum = new BigDecimal("0.00");
        if (ToolUtil.isNotEmpty(user) || ToolUtil.isNotEmpty(role)){
            if (account.equals("admin") || "chujunjun".equals(username) || account.equals(tel) ||
                    (ToolUtil.isNotEmpty(roleNames) && (roleNames.contains("出纳") || roleNames.contains("总经理")))) {
                //查看所有
                sum = btyBxdMapper.bxdSum(status, flag, beginTime, endTime, dm, xm, null);

            } else if ((ToolUtil.isNotEmpty(roleNames) && roleNames.contains("营运经理")) ||
                    (ToolUtil.isNotEmpty(role) && role.getRankName().equals("营运经理"))) {
                ymList = teamMapper.getYyYm(account);//营运经理所有店

                if (ToolUtil.isNotEmpty(ymList)) {
                    sum = btyBxdMapper.bxdSum(status, flag, beginTime, endTime, dm, xm, ymList);
                }

            } else if ((ToolUtil.isNotEmpty(roleNames) && roleNames.contains("督导")) ||
                    (ToolUtil.isNotEmpty(role) && role.getRankName().equals("督导"))) {
                ymList = teamMapper.getDdYm(account);//督导所有店

                if (ToolUtil.isNotEmpty(ymList)) {
                    sum = btyBxdMapper.bxdSum(status, flag, beginTime, endTime, dm, xm, ymList);
                }

            } else if ((ToolUtil.isNotEmpty(roleNames) && roleNames.contains("大店长")) ||
                    (ToolUtil.isNotEmpty(role) && role.getRankName().equals("大店长"))) {
                ymList = teamMapper.getDdzYm(account);//大店长所有店

                if (ToolUtil.isNotEmpty(ymList)) {
                    sum = btyBxdMapper.bxdSum(status, flag, beginTime, endTime, dm, xm, ymList);
                }
            } else if ((ToolUtil.isNotEmpty(roleNames) && roleNames.contains("店长报销单管理")) ||
                    (ToolUtil.isNotEmpty(role) && role.getRankName().equals("店长"))) {
                ymList = teamMapper.getDzYm(account);//店长所有店

                if (ToolUtil.isNotEmpty(ymList)) {
                    sum = btyBxdMapper.bxdSum(status, flag, beginTime, endTime, dm, xm, ymList);
                }
            }
        }

        return ResponseData.success(sum);
    }


    /**
     * 获取报销单详情
     */
    @RequestMapping(value = "/bxdById")
    @ResponseBody
    public ResponseData bxdById(String id, String account) {

        List<Map> list = this.btyBxdMapper.bxdById(id);
        return ResponseData.success(list);
    }

    /**
     * 查询报销人
     */
    @RequestMapping(value = "/getBxrs")
    @ResponseBody
    public ResponseData getBxrs(String xm, String account, String dm,String brandId) {
        List<BtyBxda> list = null;

        //根据电话获取用户角色
        User user = userMapper.getAccount(account);
        Team role = teamMapper.getName(account);

        String username = null;//用户名
        String roleId = null;
        List roleNames = new ArrayList();
        if (ToolUtil.isNotEmpty(user)){
            username = user.getAccount();
            roleId = user.getRoleId();//用户角色id
            List rolds = Arrays.asList(roleId.split(","));
            roleNames = userMapper.getRole(rolds);//用户角色
        }else if (ToolUtil.isNotEmpty(role)){
            username = role.getName();
        }

        String tel = "15215383999";//万总APP账号
        List<String> ymList = null;//角色所对应的店

        if (ToolUtil.isNotEmpty(user) || ToolUtil.isNotEmpty(role)){
            if (account.equals("admin") || "chujunjun".equals(username) || account.equals(tel) ||
                    (ToolUtil.isNotEmpty(roleNames) && (roleNames.contains("出纳") || roleNames.contains("总经理")))) {
                list = btyBxdMapper.getBxr(xm, null, dm);

            } else if ((ToolUtil.isNotEmpty(roleNames) && roleNames.contains("营运经理")) ||
                    (ToolUtil.isNotEmpty(role) && role.getRankName().equals("营运经理"))) {
                ymList = teamMapper.getYyYms(account,brandId);//营运经理所有店

                if (ToolUtil.isNotEmpty(ymList)) {
                    list = btyBxdMapper.getBxr(xm, ymList, dm);
                }

            } else if ((ToolUtil.isNotEmpty(roleNames) && roleNames.contains("督导")) ||
                    (ToolUtil.isNotEmpty(role) && role.getRankName().equals("督导"))) {
                ymList = teamMapper.getDdYms(account,brandId);//督导所有店

                if (ToolUtil.isNotEmpty(ymList)) {
                    list = btyBxdMapper.getBxr(xm, ymList, dm);
                }

            } else if ((ToolUtil.isNotEmpty(roleNames) && roleNames.contains("大店长")) ||
                    (ToolUtil.isNotEmpty(role) && role.getRankName().equals("大店长"))) {
                ymList = teamMapper.getDdzYms(account,brandId);//大店长所有店

                if (ToolUtil.isNotEmpty(ymList)) {
                    list = btyBxdMapper.getBxr(xm, ymList, dm);
                }
            } else if ((ToolUtil.isNotEmpty(roleNames) && roleNames.contains("店长报销单管理")) ||
                    (ToolUtil.isNotEmpty(role) && role.getRankName().equals("店长"))) {
                ymList = teamMapper.getDzYms(account,brandId);//店长所有店

                if (ToolUtil.isNotEmpty(ymList)) {
                    list = btyBxdMapper.getBxr(xm, ymList, dm);
                }
            }

            return ResponseData.success(list);
        }

        return ResponseData.success();
    }

    /**
     * 查询店名
     */
    @RequestMapping(value = "/bxdDm")
    @ResponseBody
    public ResponseData getDm(String dm, String account,String brandId) {
        List<BtyBxd> list = null;

        //根据电话获取用户角色
        User user = userMapper.getAccount(account);
        Team role = teamMapper.getName(account);

        String username = null;//用户名
        String roleId = null;
        List roleNames = new ArrayList();
        if (ToolUtil.isNotEmpty(user)){
            username = user.getAccount();
            roleId = user.getRoleId();//用户角色id
            List rolds = Arrays.asList(roleId.split(","));
            roleNames = userMapper.getRole(rolds);//用户角色
        }else if (ToolUtil.isNotEmpty(role)){
            username = role.getName();
        }

        String tel = "15215383999";//万总APP账号
        List<String> ymList = null;//角色所对应的店

        if (ToolUtil.isNotEmpty(user) || ToolUtil.isNotEmpty(role)){
            if (account.equals("admin") || "chujunjun".equals(username) || account.equals(tel) ||
                    (ToolUtil.isNotEmpty(roleNames) && (roleNames.contains("出纳") || roleNames.contains("总经理")))) {

//                list = btyBxdMapper.getDm(dm, null);
                ymList = teamMapper.getDms(account, dm,brandId);//所有店

            } else if ((ToolUtil.isNotEmpty(roleNames) && roleNames.contains("营运经理")) ||
                    (ToolUtil.isNotEmpty(role) && role.getRankName().equals("营运经理"))) {
                ymList = teamMapper.getYyDms(account, dm,brandId);//营运经理所有店

//                ymList = teamMapper.getYyYm(account);//营运经理所有店
//                if (ToolUtil.isNotEmpty(ymList)) {
//                    list = btyBxdMapper.getDm(dm, ymList);
//                }

            } else if ((ToolUtil.isNotEmpty(roleNames) && roleNames.contains("督导")) ||
                    (ToolUtil.isNotEmpty(role) && role.getRankName().equals("督导"))) {
                ymList = teamMapper.getDdDms(account, dm,brandId);//督导所有店

//                ymList = teamMapper.getDdYm(account);//督导所有店
//                if (ToolUtil.isNotEmpty(ymList)) {
//                    list = btyBxdMapper.getDm(dm, ymList);
//                }

            } else if ((ToolUtil.isNotEmpty(roleNames) && roleNames.contains("大店长")) ||
                    (ToolUtil.isNotEmpty(role) && role.getRankName().equals("大店长"))) {
                ymList = teamMapper.getDdzDms(account, dm,brandId);//大店长所有店

//                ymList = teamMapper.getDdzYm(account);//大店长所有店
//                if (ToolUtil.isNotEmpty(ymList)) {
//                    list = btyBxdMapper.getDm(dm, ymList);
//                }
            } else if ((ToolUtil.isNotEmpty(roleNames) && roleNames.contains("店长报销单管理")) ||
                    (ToolUtil.isNotEmpty(role) && role.getRankName().equals("店长"))) {
                ymList = teamMapper.getDzDms(account, dm,brandId);//店长所有店

//                ymList = teamMapper.getDzYm(account);//店长所有店
//                if (ToolUtil.isNotEmpty(ymList)) {
//                    list = btyBxdMapper.getDm(dm, ymList);
//                }
            }
//            return ResponseData.success(list);
            return ResponseData.success(ymList);
        }
        return ResponseData.success();
    }

}
